package com.hyp.service.impl;

import com.hyp.mapper.AddressMapper;
import com.hyp.pojo.Address;
import com.hyp.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class AddressServicelmpl implements AddressService {
    @Autowired
    private AddressMapper addressMapper;
    @Override
    public void addressAdd(Address address) {
        // 检查是否已有默认地址
        Address existingDefault = addressMapper.findDefaultByUserId(address.getUserId());
        if (address.getIsDefault() && existingDefault != null) {
            // 更新现有默认地址为非默认
            existingDefault.setIsDefault(false);
            addressMapper.update(existingDefault); // 需要一个update方法
        }
        address.setCreatedAt(LocalDateTime.now());
        address.setUpdatedAt(LocalDateTime.now());
        addressMapper.addressAdd(address);
    }

    @Override
    public List<Address> list(Integer userId) {
        return addressMapper.list(userId);
    }

    @Override
    public Address addressById(Integer addressId) {
        return addressMapper.addressById(addressId);
    }
}
